package com.zh.springcloud.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Description:
 * @ClassName TestTopicListener
 * @date: 2021.08.23 10:26
 * @Author: zhanghang
 */
@Component
public class TestTopicListener {

	/**
	 * description: 正常消费的队列
	 * date: 2021年-08月-23日 10:30
	 * author: zhanghang
	 * 
	 * @param msg
 * @param channel
	 * @return void
	 */ 
//	@RabbitListener(queues = "test_topic_queue_name")
	public void receiver(Message msg, Channel channel, @Headers Map<String,Object> headers) throws IOException, InterruptedException {
		try {
			//打印数据
			String message = new String(msg.getBody(), StandardCharsets.UTF_8);
			System.out.println("receiver消费消息{}"+message);
			System.out.println("headers{}"+headers);
//		channel.basicReject(msg.getMessageProperties().getDeliveryTag(), false);
			int i = 1/0; // 主动抛出异常
			channel.basicAck(msg.getMessageProperties().getDeliveryTag(),true);

		}catch (Exception e){
			System.out.println("receiver发生异常，拒绝重新入队{}");
			channel.basicReject(msg.getMessageProperties().getDeliveryTag(),false);
		}
	}


	// 监听死信队列
	@RabbitListener(queues = "test_dead_topic_queue_name")
	public void receiverDead(Message msg, Channel channel, @Headers Map<String,Object> headers) throws IOException, InterruptedException {
		//打印数据
		String message = new String(msg.getBody(), StandardCharsets.UTF_8);
		System.out.println("receiverDead{}"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		System.out.println("receiverDead消费消息{}"+message);
		System.out.println("headers{}"+headers);
		channel.basicAck(msg.getMessageProperties().getDeliveryTag(),true);
	}
}
